﻿@using SmartAdmin.Data.Models
@model IEnumerable<DataTableImportMapping>
@{
  ViewData["Title"] = "导入&导出配置";
  ViewData["PageName"] = "DataTableImportMappings_Index";
  ViewData["Heading"] = "<i class='fal fa-file-alt text-primary'></i>  导入&导出配置";
  ViewData["Category1"] = "系统管理";
  ViewData["PageDescription"] = "执行【生成】配置信息时会先删除已经存在的mapping关系，同时请更新导入模板！";
}
@section HeadBlock{
  
  <link href="~/css/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.css" rel="stylesheet" asp-append-version="true" />
  <link href="~/js/easyui/themes/insdep/easyui.css" rel="stylesheet" asp-append-version="true" />
  <link href="~/js/plugin/filepond/filepond.css" rel="stylesheet" />
}

<div class="row">
  <div class="col-lg-12 col-xl-12">
    <div id="panel-1" class="panel">
      <div class="panel-hdr">
        <h2>
          导入&导出配置
        </h2>
        <div class="panel-toolbar">
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"><i class="fal fa-window-minimize"></i></button>
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"><i class="fal fa-expand"></i></button>
          @*<button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"><i class="fal fa-times"></i></button>*@
        </div>

      </div>
      <div class="panel-container enable-loader show">
        <div class="loader"><i class="fal fa-spinner-third fa-spin-4x fs-xxl"></i></div>
        <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0  text-muted bg-faded bg-subtlelight-fade">
          <div class="row no-gutters align-items-center">
            <div class="col">
              <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") -->
              <input class="easyui-combobox"
                     name="entities"
                     id="entities"
                     data-options="
                                               url:'/DataTableImportMappings/GetAllEntites',
                                        method:'get',
                                        valueField:'Name',
                                        textField:'Value',
                                        panelHeight:'auto'
                                        ">
              <div class="btn-group">
                <button name="searchbutton" onclick="reloadData()" class="btn btn-sm btn-default"> <i class="fal fa-search mr-1"></i> 刷新 </button>
              </div>
              <div class="btn-group">
                <button name="createbutton"  onclick="generate()" class="btn btn-sm btn-primary"> <i class="fal fa-plus mr-1"></i> 生成配置 </button>
              </div>

              <div class="btn-group">
                <button name="createtmpbutton" onclick="createexceltemplate()" class="btn btn-sm btn-primary"> <i class="fal fa-file-archive mr-1"></i> 生成模板 </button>
              </div>
              <div class="btn-group">
                <button  name="importbutton" onclick="importconfig()" class="btn btn-sm   btn-primary"> <i class="fal fa-upload mr-1"></i> 导入配置 </button>
</div>
              <div class="btn-group">
                <button name="exporttbutton" onclick="exportexcel()" class="btn btn-sm   btn-info"> <i class="fal fa-download mr-1"></i> 导出配置 </button>
</div>
              <div class="btn-group">
                <button name="deletebutton" disabled onclick="removeData()"  class="btn btn-sm btn-danger"> <i class="fal fa-trash-alt mr-1"></i> 删除 </button>
</div>
              <div class="btn-group">
                <button name="savebutton" disabled onclick="acceptChanges()" class="btn btn-sm btn-default"> <i class="fal fa-save mr-1"></i> 保存 </button>
              </div>

              <div class="btn-group">
                <button name="savebutton"  onclick="rejectChanges()" class="btn btn-sm btn-default"> <i class="fal fa-times-circle mr-1"></i> 取消 </button>
</div>
            </div>

          </div>

        </div>
        <div class="panel-content">
          <div class="table-responsive">
            <table id="datatableimportmappings_datagrid"></table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- MAIN CONTENT -->



<div class="modal fade" id="importModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">上传配置</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

      </div>
      <div class="modal-body">

        <input type="file"
               class="filepond"
               name="filepond" multiple
               accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
               data-max-file-size="50MB"
               data-max-files="100">


      </div>

    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div>

@section ScriptsBlock {
  <script src="~/js/dependency/moment/moment.js" asp-append-version="true"></script>
  
  <script src="~/js/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.js" asp-append-version="true"></script>
  <script src="~/js/easyui/jquery.easyui.min.js" asp-append-version="true"></script>
  <script src="~/js/easyui/plugins/datagrid-filter.js" asp-append-version="true"></script>
  <script src="~/js/easyui/plugins/columns-ext.js" asp-append-version="true"></script>
  <script src="~/js/easyui/plugins/columns-reset.js" asp-append-version="true"></script>
  <script src="~/js/easyui/locale/easyui-lang-zh_CN.js" asp-append-version="true"></script>
  <script src="~/js/easyui/jquery.easyui.component.js" asp-append-version="true"></script>
  <script src="~/js/jquery.extend.formatter.js" asp-append-version="true"></script>
  <script src="~/js/jquery.custom.extend.js" asp-append-version="true"></script>
  <script src="~/js/plugin/filesaver/FileSaver.js" asp-append-version="true"></script>
  <script src="~/js/plugin/filesaver/jquery.fileDownload.js" asp-append-version="true"></script>
  <script src="~/js/plugin/jquery.serializejson/jquery.serializejson.js" asp-append-version="true"></script>
  <script src="~/js/plugin/filepond/filepond.min.js" asp-append-version="true"></script>
  <script src="~/js/plugin/filepond/plugin/filepond-plugin-file-validate-type.min.js"></script>
  <script src="~/js/plugin/filepond/plugin/filepond-plugin-file-validate-size.min.js"></script>
  <script type="text/javascript">
    //全屏事件
    document.addEventListener('panel.onfullscreen', () => {
      $dg.treegrid('resize');
    });
            //上传导入参数设定
    const entityname = "DataTableImportMapping";
    function reloadData() {
      $dg.datagrid('reload');
    }
    function print() {
      $dg.datagrid('print', 'DataGrid');
    }
    function configFilePond() {
      FilePond.registerPlugin(
        FilePondPluginFileValidateType,
        FilePondPluginFileValidateSize
      );
      FilePond.setOptions({
        instantUpload: true,
        server: {
          timeout: 7000,
          process: {
            url: '/DataTableImportMappings/ImportConfig',
            method: 'POST',
            ondata: (formData) => {
              formData.append('label', 'importconfig');
              return formData;
            },
            onerror: (response) => {
              console.log(response);
            },
            onload: (response) => {
              setTimeout(() => {
                $('#importModal').modal('toggle');
                reloadData();
              }, 1000);

            },
          },
          revert: '/DataTableImportMappings/Revert',
        },

      })


    }

    //let pond;
    const inputElement = document.querySelector('input[type="file"]');
    const pond = FilePond.create(inputElement);

    function importconfig () {
      $('#importModal').modal('toggle');
    }
    //导出Excel
    function exportexcel() {
      const filterRules = JSON.stringify($dg.datagrid('options').filterRules);
      //console.log(filterRules);
      $.messager.progress({ title: '正在执行导出!' });
      let formData = new FormData();
      formData.append('filterRules', filterRules);
      formData.append('sort', 'Id');
      formData.append('order', 'asc');
      $.postDownload('/DataTableImportMappings/ExportExcel', formData).then(res => {
        $.messager.progress('close');
        toastr.success('导出成功!');
      }).catch(err => {
        $.messager.progress('close');
        $.messager.alert('导出失败', err.statusText, 'error');
      });
    }
    function generate() {
      var entityname = $('#entities').combobox('getValue');
      if (entityname.length > 0) {
        $.messager.progress({ title: '正在处理请耐心等待！' });
        $.post('/DataTableImportMappings/Generate', { entityname: entityname }, function (data, textStatus, jqXHR) {
          //console.log(data);
          $.messager.progress('close');
          $.messager.alert("提示", "生成完成！", 'info', function () {
            $dg.datagrid('reload');
          });

        });
      } else {
        $.messager.alert("提示", "请选中需要生成Mapping关系的实体类！");
        $('#entities').focus();
      }

    }
    function createexceltemplate() {
      var entityname = $('#entities').combobox('getValue');
      if (entityname.length > 0) {
        $.messager.progress({ title: '正在处理请耐心等待！' });
        $.post('/DataTableImportMappings/CreateExcelTemplate', { entityname: entityname }, function (data, textStatus, jqXHR) {
          //console.log(data);
          $.messager.progress('close');
          if (data.success) {
            $.messager.alert("提示", "创建完成！", 'info', function () {
              $dg.datagrid('reload');
            });
          } else {
            $.messager.alert("错误", data.message, 'error')
          }
        });
      } else {
        $.messager.alert("提示", "请选中需要生成模板的实体类！");
        $('#entities').focus();
      }
    }




    function importexcel() {
      $('#importwindow').window('open');
    }

            var $dg = $('#datatableimportmappings_datagrid');
            var editIndex = undefined;
    function endEditing() {
      if (editIndex == undefined) { return true }
      if ($dg.datagrid('validateRow', editIndex)) {

        $dg.datagrid('endEdit', editIndex);
        editIndex = undefined;


        return true;
      } else {
        return false;
      }
    }
    function onClickCell(index, field) {
      if (editIndex != index) {
        if (endEditing()) {
          $dg.datagrid('selectRow', index)
            .datagrid('beginEdit', index);
          var ed = $dg.datagrid('getEditor', { index: index, field: field });
          if (ed) {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
          }
          editIndex = index;
        } else {
          $dg.datagrid('selectRow', editIndex);
        }
      }
    }

    function removeData() {
      deletechecked();
      hook = false;
    }
    function deletechecked() {
      const id = $dg.datagrid('getChecked').filter(item => item.Id != null && item.Id > 0).map(item => {
        return item.Id;
      });;
      if (id.length > 0) {
        $.messager.confirm('确认', `你确定要删除这 <span class='badge badge-icon position-relative'>${id.length} </span> 行记录?`, result => {
          if (result) {
            dodeletechecked(id);
          }
        });
      } else {
        $.messager.alert('提示', '请先选择要删除的记录!', 'question');
      }
    }
    //执行删除
    function dodeletechecked(id) {
      $.post('/DataTableImportMappings/DeleteChecked', { id: id })
        .done(response => {
          if (response.success) {
            toastr.error(`成功删除[${id.length}]行记录`);
            reloadData();
          } else {
            $.messager.alert('错误', response.err, 'error');
          }
        })
        .fail((jqXHR, textStatus, errorThrown) => {
          $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
        });
    }

    function acceptChanges() {
      if (endEditing()) {
        if ($dg.datagrid('getChanges').length>0) {
          const inserted = $dg.datagrid('getChanges', 'inserted').map(item => {
          item.TrackingState = 1;
          return item;
        });
        const updated = $dg.datagrid('getChanges', 'updated').map(item => {
          item.TrackingState = 2
          return item;
        });
        const deleted = $dg.datagrid('getChanges', 'deleted').map(item => {
          item.TrackingState = 3
          return item;
        });
          const changed = inserted.concat(updated.filter(item => {
            return !deleted.includes(item);
          })).concat(deleted);
          //console.log(JSON.stringify(changed));
          $.post("/DataTableImportMappings/SaveData",  {datatableimportmappings:changed}, function (res) {
            //console.log(res);
            if (res.success) {
              $.messager.alert("提示", "保存成功！");
              $dg.datagrid('acceptChanges');
              $dg.datagrid('reload');
              $dg.datagrid('uncheckAll');
            }
          }, "json").fail(function () {
            $.messager.alert("错误", "提交错误了！", 'error');

          });

        }


      }
    }
    function rejectChanges() {
      $dg.datagrid('rejectChanges');
      $dg.datagrid('uncheckAll');
      editIndex = undefined;
    }



    $(function () {
      configFilePond();
      $dg.datagrid({
        idField: 'Id',
        sortName: 'EntitySetName',
        sortorder: 'asc',
        rownumbers: true,
        remoteFilter: true,
        singleSelect: false,
        pageList: [10, 20, 50, 100, 500],
        method: 'get',
        onClickCell: onClickCell,
         clientPaging: false,
        pagination: 'true',
        onBeforeLoad: function () {
          $('.enable-loader').removeClass('enable-loader')
        },
        onCheckAll: function (rows) {
          if (rows.length > 0) {
            $("button[name*='deletebutton']").prop('disabled', false);
          }
        },
        onCheckAll: function (rows) {
          if (rows.length > 0) {
            $("button[name*='deletebutton']").prop('disabled', false);
          }
        },
        onCheck: function () {
          $("button[name*='deletebutton']").prop('disabled', false);
        },
        onUncheckAll: function () {
          $("button[name*='deletebutton']").prop('disabled', true);
        },
        onBeforeEdit: function (index, row) {
          row.editing = true;
          $("button[name*='deletebutton']").prop('disabled', false);
          $("button[name*='savebutton']").prop('disabled', false);
          $("button[name*='cancelbutton']").prop('disabled', false);
          $(this).datagrid('refreshRow', index);
        },
        onBeginEdit:function(rowIndex,row){
          var editors = $(this).datagrid('getEditors', rowIndex);
          var n2 = $(editors[3].target).combobox({
            value:row.IgnoredColumn
          });
          var n1 = $(editors[2].target).combobox({
            value: row.IsEnabled,
            onSelect: function (item) {
              if (item.value === 'true') {
                n2.combobox('setValue', 'true');
              }
              else {
                n2.combobox('setValue', 'false');
              }
            }

          });

      },
        onLoadSuccess: function (data) {
          editIndex = undefined;
          $("button[name*='deletebutton']").prop('disabled', true);
          $("button[name*='savebutton']").prop('disabled', true);
          $("button[name*='cancelbutton']").prop('disabled', true);
        },
        frozenColumns: [[
          /*开启CheckBox选择功能*/
          { field: 'ck', checkbox: true },
        ]],
        columns: [[
          { field: 'Id', width: 80, hidden: true, resizable: true, title: '@Html.DisplayNameFor(model => model.Id)' },
          { field: 'EntitySetName', width: 140, resizable: true, sortable: true,title: '@Html.DisplayNameFor(model => model.EntitySetName)' },
          { field: 'FieldName', width: 140, title: '@Html.DisplayNameFor(model => model.FieldName)' },
          { field: 'TypeName', width: 140, title: '@Html.DisplayNameFor(model => model.TypeName)' },
          { field: 'IsRequired', formatter: booleanformatter, width: 100, title: '@Html.DisplayNameFor(model => model.IsRequired)' },
          { field: 'DefaultValue', width: 140, editor: { type: 'textbox', options: { required: false } }, title: '@Html.DisplayNameFor(model => model.DefaultValue)' },
          { field: 'SourceFieldName', width: 140, editor: { type: 'textbox', options: { required: false } }, title: '@Html.DisplayNameFor(model => model.SourceFieldName)' },
          {
            field: 'IsEnabled', width: 100, editor: {
              type: 'combobox',
              options: {
                panelHeight: 'auto',
                data: [{ value: 'true', text: '是' }, { value: 'false', text: '否' }],
                required: true
              }
            }, title: '@Html.DisplayNameFor(model => model.IsEnabled)',
            formatter: booleanformatter
          },
          {
            field: 'IgnoredColumn', width: 100, editor: {
              type: 'combobox',
              options: {
                panelHeight: 'auto',
                data: [{ value: 'true', text: '是' }, { value: 'false', text: '否' }],
                required: true
              }
            },
            formatter: booleanformatter,
            title: '@Html.DisplayNameFor(model => model.IgnoredColumn)'
          },
          { field: 'RegularExpression', width: 190, editor: { type: 'textbox', options: { required: false } }, title: '@Html.DisplayNameFor(model => model.RegularExpression)' }
        ]]

      })
      .datagrid('enableFilter', [
        {
          field: 'EntitySetName',
          type: 'combobox',
          options: {
            panelHeight: 'auto',
            url: '/DataTableImportMappings/GetAllEntites',
            method: 'get',
            valueField: 'Name',
            textField: 'Value',
            onChange: function (value) {
              if (value == '') {
                $dg.datagrid('removeFilterRule', 'EntitySetName');
              } else {
                $dg.datagrid('addFilterRule', {
                  field: 'EntitySetName',
                  op: 'equal',
                  value: value
                });
              }
              $dg.datagrid('doFilter');
            }
          }
        },
        {
          field: 'IsRequired',
          type: 'combobox',
          options: {
            panelHeight: 'auto',
            data: [{ value: '', text: 'All' }, { value: 'true', text: '是' }, { value: 'false', text: '否' }],
            onChange: function (value) {
              if (value == '') {
                $dg.datagrid('removeFilterRule', 'IsRequired');
              } else {
                $dg.datagrid('addFilterRule', {
                  field: 'IsRequired',
                  op: 'equal',
                  value: value
                });
              }
              $dg.datagrid('doFilter');
            }
          }
        },
        {
          field: 'IsEnabled',
          type: 'combobox',
          options: {
            panelHeight: 'auto',
            data: [{ value: '', text: 'All' }, { value: 'true', text: '是' }, { value: 'false', text: '否' }],
            onChange: function (value) {
              if (value == '') {
                $dg.datagrid('removeFilterRule', 'IsEnabled');
              } else {
                $dg.datagrid('addFilterRule', {
                  field: 'IsEnabled',
                  op: 'equal',
                  value: value
                });
              }
              $dg.datagrid('doFilter');
            }
          }
        },
        {
          field: 'IgnoredColumn',
          type: 'combobox',
          options: {
            panelHeight: 'auto',
            data: [{ value: '', text: 'All' }, { value: 'true', text: '是' }, { value: 'false', text: '否' }],
            onChange: function (value) {
              if (value == '') {
                $dg.datagrid('removeFilterRule', 'IgnoredColumn');
              } else {
                $dg.datagrid('addFilterRule', {
                  field: 'IgnoredColumn',
                  op: 'equal',
                  value: value
                });
              }
              $dg.datagrid('doFilter');
            }
          }
        }

      ])
        .datagrid('load', '/DataTableImportMappings/GetData');
    });
  </script>

}

